import { Injectable } from "@nestjs/common";
import * as crypto from "crypto"
import * as querystring from "querystring"


@Injectable()
export class XfService {
  getUrl() {
    const Host = "ws-api.xf-yun.com"
    const HttpProto = "HTTP/1.1"
    const RequestUri = "/v1/simult_interpretation"
    const appID = "4c4d8fad"
    const APISecret = "MTkxY2NmN2RlMDMxYjBhOWY0NmE4OTYy"
    const APIKey = "e5254273f1fa1e3731ef1b346d546976"
    const url = `ws://${Host}${RequestUri}`

    // Generate RFC1123 formatted date
    const date = new Date().toUTCString();
    
    // Construct the signature origin
    let signatureOrigin = `host: ${Host}\n`;
    signatureOrigin += `date: ${date}\n`;
    signatureOrigin += `GET ${RequestUri} HTTP/1.1`;

    // Calculate the HMAC SHA256 signature
    const signatureSha = crypto.createHmac('sha256', APISecret).update(signatureOrigin).digest('base64');
    
    // Construct the authorization string
    const authorizationOrigin = `api_key="${APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${signatureSha}"`;
    const authorization = Buffer.from(authorizationOrigin).toString('base64');
    
    // Construct the parameters object
    const parameters = {
        authorization: authorization,
        date: date,
        host: Host,
        serviceId: "simult_interpretation"
    };
    
    // Append parameters to the URL
    const queryString = querystring.stringify(parameters);
    const finalUrl = `${url}?${queryString}`;
    return {url: finalUrl}
  }
}